package org.chench.test.gatewayzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Desc: 在服务网关进行过滤，检查token参数是否存在
 * Name: org.chench.test.gatewayzuul.filter.MyFilter
 * Author: chench9@lenovo.com
 * Date: 2018/4/19 20:45
 **/
@Component
public class TokenFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        // 过滤类型，pre：路由之前, route：路由时过滤, post: 路由之后过滤，在route和error之后, error: 发生错误时过滤,不发生错误不会过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 过滤顺序，如果同时存在多个Filter，值越大，越先被调用
        return 20;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行过滤
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        logger.info("Do filter, {} >>> {}", request.getMethod(), request.getRequestURI());
        Object token = request.getParameter("token");
        if(token == null) {
            logger.error("Token is Empty!");
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(400);
            try {
                context.getResponse().getWriter().write("token is empty!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        logger.info("Filter OK!!!");
        return null;
    }
}
